var qcloud = require('../../vendor/wafer2-client-sdk/index')
var util = require('../../utils/util.js')
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    isAuth: true
  },
  onLoad: function () {
    if (!app.$store.isAuth) {
      app.wxGetSettingReadyCallback = res => {
        this.setData({
          isAuth: res === 1
        })
        this.changeAuth(res === 1)
      }
    } else {
      this.changeAuth(app.$store.isAuth === 1)
    }
  },
  changeAuth (status) {
    if (status) {
      this.setData({
        isAuth: true
      })
      this.login()
    } else {
      this.setData({
        isAuth: false
      })
      if (!wx.canIUse('button.open-type.getUserInfo')) {
        this.login()
      }
    }
  },
  handerGetUserInfo (event) {
    if (event.detail.rawData) {
      console.log(JSON.parse(event.detail.rawData))
      this.setData({
        isAuth: true
      })
      this.login()
    } else {
      util.showModel('授权失败','请先微信授权登录后放心使用通信科协小程序，你的信息和数据将受到保护');
    }
  },
  login () {
    wx.showLoading({
      title: '登录中',
      mask: true
    });
    const session = qcloud.Session.get()
    if (session) {
      // 第二次登录
      // 或者本地已经有登录态
      // 可使用本函数更新登录态
      qcloud.loginWithCode({
        success: res => {
          wx.hideLoading()
          this.checkUser(res)
        },
        fail: err => {
          wx.hideLoading()
          console.log(err)
          util.showModel('登录失败', err)
        }
      })
    } else {
      // 首次登录
      qcloud.login({
        success: res => {
          wx.hideLoading()
          this.checkUser(res)
        },
        fail: err => {
          wx.hideLoading()
          console.log(err)
          util.showModel('登录失败', err)
        }
      })
    }
  },
  checkUser (userInfo) {
    if (!userInfo.state) {
      wx.redirectTo({
        url: '../bind/bind'
      })
    } else if (userInfo.state === '1')
    {
      app.$store.stuid = userInfo.stuid
      wx.switchTab({
        url: '../main/main'
      })
    } else if (userInfo.state === '2')
    {
      app.$store.stuid = userInfo.stuid
      wx.redirectTo({
        url: '../recruit/recruit'
      })
    } else if (userInfo.state === '3') {
      app.$store.stuid = userInfo.stuid
      app.$store.recruit_info = userInfo.info
      wx.redirectTo({
        url: '../recruited/recruited'
      })
    }
  }
})
